package com.wswy.wzcx.ui.persenter;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;

import com.blankj.utilcode.util.Utils;
import com.che.libcommon.api.ApiOptionalResultObserver;
import com.che.libcommon.api.BaseResult;
import com.che.libcommon.api.ProgressDialogObserver;
import com.che.libcommon.api.VoidResultObserver;
import com.che.libcommon.utils.IntentUtils;
import com.che.libcommon.utils.RxBus;
import com.che.libcommon.utils.ToastUtils;
import com.che.libcommon.utils.optional.Optional;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.wswy.wzcx.AppContext;
import com.wswy.wzcx.BuildConfig;
import com.wswy.wzcx.api.Api;
import com.wswy.wzcx.model.DataCenter;
import com.wswy.wzcx.model.UserMode;
import com.wswy.wzcx.model.core.OSSUploadResult;
import com.wswy.wzcx.model.resp.WXLoginResp;
import com.wswy.wzcx.module.InternalMsgCode;
import com.wswy.wzcx.module.core.BasePresenter;
import com.wswy.wzcx.statistics.StatTools;
import com.wswy.wzcx.statistics.StatisticsId;
import com.wswy.wzcx.ui.dialog.ChoosePhotoBottomDialog;
import com.wswy.wzcx.ui.view.UserInfoView;
import com.wswy.wzcx.utils.ShareHelper;
import com.wswy.wzcx.widget.ChooseBottomDialog;

import io.reactivex.Single;
import io.reactivex.SingleSource;
import io.reactivex.functions.Function;
import io.reactivex.observers.ResourceObserver;
import io.reactivex.schedulers.Schedulers;
import java.io.File;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import io.reactivex.SingleObserver;
import io.reactivex.disposables.Disposable;
import top.zibin.luban.Luban;

/**
 * Created by wangduheng26 on 2018/1/24.
 * wangduheng26@gmail.com
 */

public class UserInfoPresenter extends BasePresenter{
    private static final int REQ_FROM_PHOTO_GALLERY = 32; //从相册中选择
    private static final int REQ_FROM_CAMERA = 36; //拍照
    private UserInfoView mView;
    private String currImgFile = null;
    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1000);


    private String wxLoginReqSign = null;

    public UserInfoPresenter(UserInfoView view) {
        this.mView = view;
    }

    @Override
    public void onCreate(@Nullable Bundle bundle) {
        super.onCreate(bundle);

        if (DataCenter.get().hasLogin()){
            Api.get().getUserInfo().subscribe(new ApiOptionalResultObserver<UserMode>(){

                @Override
                protected void onApiResult(@Nullable UserMode mode) {
                    if (mode != null){
                        DataCenter.get().saveUserModeWithoutNotify(mode);
                    }
                }

                @Override
                protected void onApiError(@Nullable BaseResult result) {

                }
            });
        }



    }

    @Override
    protected void registerObservers() {
        super.registerObservers();

        ResourceObserver<WXLoginResp> wxLoginObserver = new ResourceObserver<WXLoginResp>() {
            @Override
            public void onNext(WXLoginResp resp) {
//                onUserLoginSuccess(userMode);

                if (resp.errCode == 0 && TextUtils.equals(wxLoginReqSign,resp.state)){
                    bindWechat(resp.code);
                }else {
                    ToastUtils.showText(resp.getErrorMsg());
                }
                wxLoginReqSign = null;
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        };

        RxBus.getDefault().toObservableWithCode(InternalMsgCode.CODE_WX_LOGIN,WXLoginResp.class)
                .subscribe(wxLoginObserver);
        disposables.add(wxLoginObserver);
    }

    @Override
    protected void onUserLoginSuccess(UserMode userMode) {
        super.onUserLoginSuccess(userMode);
        mView.dataChanged();
    }

    @Override
    protected void onLogout() {
        mView.dataChanged();
    }

    public void showChooseBottomDialog() {
        ChooseBottomDialog dialog = new ChoosePhotoBottomDialog(mView.activity());
        dialog.setOnItemClickListener(new ChooseBottomDialog.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                switch (position) {
                    case 0:
                        startCamera();
                        break;
                    case 1:
                        startGallery();
                        break;
                    case 2:
                        break;

                }
            }
        });
        dialog.show();
    }

    private void startCamera() {
        final Activity activity = mView.activity();
        if ( !(activity instanceof FragmentActivity)){
            return;
        }
        RxPermissions permissions = new RxPermissions((FragmentActivity)activity);
        permissions.request(Manifest.permission.CAMERA)
                .singleOrError()
                .subscribe(new SingleObserver<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onSuccess(Boolean aBoolean) {
                        if (aBoolean) {
                            currImgFile = generateFile();
                            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            Uri contentUri = null;
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                contentUri = FileProvider.getUriForFile(activity, BuildConfig.APPLICATION_ID + ".fileprovider", new File(currImgFile));
                            } else {
                                contentUri = Uri.fromFile(new File(currImgFile));
                            }

                            intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, contentUri);
                            mView.fragment().startActivityForResult(intent, REQ_FROM_CAMERA);
                        }

                    }

                    @Override
                    public void onError(Throwable e) {

                    }
                });

    }

    private String generateFile() {
        return new File(mView.activity().getExternalFilesDir("photo"), "IMG_" + System.currentTimeMillis() + "_" + sNextGeneratedId.incrementAndGet() + ".jpg").getAbsolutePath();
    }

    private void startGallery() {
        final Activity activity = mView.activity();

        if ( !(activity instanceof FragmentActivity)){
            return;
        }

        RxPermissions permissions = new RxPermissions((FragmentActivity) activity);
        permissions.request(Manifest.permission.READ_EXTERNAL_STORAGE)
                .singleOrError()
                .subscribe(new SingleObserver<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onSuccess(Boolean aBoolean) {
                        if (aBoolean) {
                            mView.fragment().startActivityForResult(IntentUtils.getPickGallery(), REQ_FROM_PHOTO_GALLERY);
                        }

                    }

                    @Override
                    public void onError(Throwable e) {

                    }
                });
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQ_FROM_PHOTO_GALLERY) {
                if (data != null) {
                    String img = IntentUtils.extraImageFromGallery(mView.activity(),data);
                    if (!TextUtils.isEmpty(img)) {
                        saveHeader(img);
                    }
                }
            } else if (requestCode == REQ_FROM_CAMERA) {
                if (currImgFile != null) {
                    File file = new File(currImgFile);
                    if (file.exists() && file.isFile() && file.length() > 0) {
                        String path = currImgFile;
                        saveHeader(path);
                    }
                }
                currImgFile = null;
            }
        }

    }

    private void saveHeader(String path) {
        File file = new File(path);
        if (file.exists() && file.isFile()) {

            Single.just(path).observeOn(Schedulers.io()).map(new Function<String, File>() {
                @Override
                public File apply(String path) throws Exception {
                    return Luban.with(Utils.getApp()).get(path);
                }
            }).flatMap(new Function<File, SingleSource<Optional<String>>>() {
                @Override
                public SingleSource<Optional<String>> apply(File file) throws Exception {
                    final String key = "headImg";
                    return Api.get().uploadFiles("avatar", Collections.singletonMap(key,file)).map(
                        new Function<Map<String, OSSUploadResult>, Optional<String>>() {
                            @Override
                            public Optional<String> apply(Map<String, OSSUploadResult> fileOSSUploadResultMap)
                                throws Exception {

                                return Optional.ofNullable(fileOSSUploadResultMap.get(key).getObjectKey());
                            }
                        });
                }
            }).flatMap(new Function<Optional<String>, SingleSource<Optional<UserMode>>>() {
                @Override
                public SingleSource<Optional<UserMode>> apply(Optional<String> stringOptional) throws Exception {
                    return Api.get().submitUserInfoHeader(stringOptional.orNull());
                }
            })

//            Single.just(path).observeOn(Schedulers.io()).map(new Function<String, File>() {
//                @Override
//                public File apply(String path) throws Exception {
//                    return Luban.with(Utils.getApp()).get(path);
//                }
//            }).flatMap(new Function<File, SingleSource<Optional<UserMode>>>() {
//                @Override
//                public SingleSource<Optional<UserMode>> apply(File file) throws Exception {
//                    return Api.get().submitUserInfoHeader(file.getAbsoluteFile());
//                }
//            })
 .subscribe(new ProgressDialogObserver<UserMode>(mView.fragment().getContext()) {
                        @Override
                        protected void onApiResult(@Nullable UserMode userMode) {
                            DataCenter.get().updateUserMode(userMode);
                            ToastUtils.showText("保存成功");
                            mView.dataChanged();
                        }

                        @Override
                        protected void onApiError(@Nullable BaseResult result) {
                            toastErrorMsg(result);
                        }
                    });

        }

    }


    public void unbindWechat(){
        Api.get().userWechatUnbind().subscribe(new VoidResultObserver(){
            @Override
            protected void onSuccess() {
                super.onSuccess();
                UserMode userMode = DataCenter.get().getUserMode();
                if (userMode != null){
                    userMode.wechatBind = false;
                    DataCenter.get().saveUserModeWithoutNotify(userMode);

                    StatTools.sendClick(AppContext.getContext(),StatisticsId.mine_account_wx_qx);

                }
                mView.dataChanged();
                ToastUtils.showText("解除绑定成功");
            }
        });
    }

    public void starWechatBind(){
        wxLoginReqSign = ShareHelper.login();
    }

    private void bindWechat(String code){

        Api.get().userWechatBind(code).subscribe(new ProgressDialogObserver<Object>(mView.activity()){

            @Override
            protected void onApiResult(@Nullable Object mode) {
                //
                UserMode userMode = DataCenter.get().getUserMode();
                if (userMode != null){
                    userMode.wechatBind = true;
                    DataCenter.get().saveUserModeWithoutNotify(userMode);

                    StatTools.sendClick(AppContext.getContext(),StatisticsId.mine_account_wx_bd);

                }
                mView.dataChanged();
                ToastUtils.showText("绑定成功");
            }

            @Override
            protected void onApiError(@Nullable BaseResult result) {
                toastErrorMsg(result);
            }
        });

    }

}
